import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:logger/logger.dart';

typedef ProgressBarCallback = void Function(double value);

enum LightControlBarType { brightness, colorTemp }

class LightControlBar extends StatefulWidget {
  const LightControlBar({
    super.key,
    required this.value,
    this.barColor = Colors.white,
    this.barColorList,
    this.barWidth = 90,
    this.iconName,
    this.backgroundColor = const Color.fromRGBO(79, 79, 79, 0.5),
    this.lightControlBarType = LightControlBarType.brightness,
    required this.valueDidChanged,
    required this.valueChangedDidEnd,
  });

  final double value; // 当前数值0-1
  final Color barColor; // 进度条颜色
  final List<Color>? barColorList; //进度条渐变色数组
  final double barWidth; // 进度条宽度
  final Color backgroundColor; // 背景色
  final String? iconName; // 图标名称
  final LightControlBarType lightControlBarType; //进度条类型
  final ProgressBarCallback valueDidChanged; // 滑动数值变动返回
  final ProgressBarCallback valueChangedDidEnd; // 滑动结束回调

  @override
  State<LightControlBar> createState() {
    return _LightControlBarState();
  }
}

// 混入 AutomaticKeepAliveClientMixin 进行组件缓存
class _LightControlBarState extends State<LightControlBar>
    with AutomaticKeepAliveClientMixin {
  double _superHeight = 0;
  double _progressValue = 0;
  bool _dragStart = false;
  double fiftyHeight=50.r;
  // 设置为 true 则表示保存页面状态
  @override
  bool get wantKeepAlive => true;

  @override
  void didUpdateWidget(covariant LightControlBar oldWidget) {
    _progressValue = _superHeight * widget.value;
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // 获取到组件高度直接创建页面
    return LayoutBuilder(builder: (context, constraints) {
      if (_superHeight == 0) {
        _superHeight = constraints.biggest.height.roundToDouble() -
            fiftyHeight; // 获取组件在父组件所能设置的最大高度
        _progressValue = _superHeight * widget.value;
      }
      return _buildProgressWidget(context);
    });
  }

  Widget _buildProgressWidget(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onPanDown: (value) {
        double newOffset = _superHeight - value.localPosition.dy + fiftyHeight;
        if (newOffset > _superHeight) {
          newOffset = _superHeight;
        }
        // 拖动改变位置
        _poffsetCahanged(newOffset);
      },
      onVerticalDragStart: (value) {
        // Logger().d('手指开始垂直滑动');
        _dragStart = true;
      },
      onVerticalDragUpdate: (value) {
        // Logger().d(
        //     '正在垂直滑动-${value.globalPosition}---${value.localPosition}---${value.delta}');

        double newOffset = _progressValue - value.delta.dy;
        // 拖动改变位置
        _poffsetCahanged(newOffset);
      },
      onVerticalDragEnd: (value) {
        _dragStart = false;
        // setState(() {});
        // Logger().d('手指垂直滑动结束');
      },
      onVerticalDragCancel: () {
        _dragStart = false;
        // Logger().d('滑动取消');
      },
      child: Container(
        // color: Colors.transparent,
        padding: const EdgeInsets.only(top: 50).r,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(25).r,
          child: SizedBox(
            width: widget.barWidth.w,
            child: Stack(
              alignment: AlignmentDirectional.bottomCenter,
              children: [
                Container(
                  height: _superHeight,
                  decoration: BoxDecoration(
                    color: widget.backgroundColor,
                    borderRadius: BorderRadius.all(const Radius.circular(25).r),
                  ),
                ),
                widget.lightControlBarType == LightControlBarType.brightness
                    ? AnimatedContainer(
                        duration: Duration(milliseconds: _dragStart ? 0 : 400),
                        curve: Curves.easeOutCubic,
                        height: _progressValue,
                        color: widget.barColor,
                      )
                    : Container(
                        height: _superHeight,
                        decoration: BoxDecoration(
                          color: widget.barColor,
                          gradient: widget.barColorList!.isNotEmpty
                              ? LinearGradient(
                                  colors: widget.barColorList!,
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter)
                              : null, //渐变从上到下),
                        )),
                widget.lightControlBarType == LightControlBarType.colorTemp
                    ? Positioned(
                        bottom: _iconPosion,
                        child: Container(
                          width: 88.w,
                          height: 22.r,
                          padding: const EdgeInsets.fromLTRB(28, 8, 28, 8).r,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10).r,
                            boxShadow: const [
                              BoxShadow(
                                  color: Color.fromRGBO(0, 0, 0, 0.21),
                                  offset: Offset(0, 3),
                                  blurRadius: 25)
                            ],
                          ),
                          child: Container(
                            decoration: BoxDecoration(
                                color: const Color.fromRGBO(50, 50, 50, 0.8),
                                borderRadius: BorderRadius.circular(5.r)),
                          ),
                        ))
                    : Positioned(
                        bottom: fiftyHeight,
                        child: SizedBox(
                          width: 28.r,
                          height: 28.r,
                          child: SvgPicture.asset(
                            widget.iconName!,
                            color: const Color.fromRGBO(138, 138, 138, 1),
                          ),
                        ))
              ],
            ),
          ),
          // ),
        ),
      ),
    );
  }

  // 手势位置发生变化
  void _poffsetCahanged(double newOffset) {
    if (newOffset >= 0 && newOffset <= _superHeight) {
      _progressValue = newOffset;

      double percent = newOffset / _superHeight;

      if (widget.lightControlBarType == LightControlBarType.brightness) {
        percent = double.parse(percent.toStringAsFixed(2));
      } else {
        percent = double.parse(percent.toStringAsFixed(4));
        if (percent > 0.9990) {
          percent = 1;
        } else if (percent < 0.0009) {
          percent = 0;
        }
      }

      // Logger().d('滑动百分比:$percent');
      widget.valueDidChanged(percent);
      setState(() {
        if (percent == 0) {
          _progressValue = 0;
        } else if (percent == 1) {
          _progressValue = _superHeight;
        }
      });
    }
  }

  double get _iconPosion {
    double topSpace =
        (widget.lightControlBarType == LightControlBarType.brightness
            ? 8.r
            : 30.r);
    double bottomSpace =
        widget.lightControlBarType == LightControlBarType.brightness
            ? 4.r
            : 8.r;
    double iconPosion = 4.r;
    // 设置icon图标
    if (_progressValue <= topSpace + bottomSpace) {
      iconPosion = bottomSpace;
    } else {
      iconPosion = _progressValue - topSpace;
    }
    // print('图标底部位置------$iconPosion, -----手势滑动位置 ---- $_progressValue');
    return iconPosion;
  }
}
